package com.atguigu.gulimaill.cart.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimaill.cart.service.CartService;
import com.atguigu.gulimaill.cart.vo.CartItemVo;
import com.atguigu.gulimaill.cart.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Slf4j
@Controller
public class CartController {
    @Autowired
    CartService cartService;


    @GetMapping("/currentUserCartItems")
    @ResponseBody
    public R currentUserCartItems() {
        List<CartItemVo> cartItems = cartService.getCurrentUserCartItems();
        return R.ok().put("data",cartItems);
    }


    @GetMapping("/cart.html")
    public String cartListPage(Model model) {
        CartVo cartVo= cartService.getCart();
        model.addAttribute("cart", cartVo);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String success(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {

        cartService.addToCart(skuId, num);
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addToCartsuccess.html";
    }

    @GetMapping("/addToCartsuccess.html")
    public String successPage(@RequestParam("skuId") Long skuId, Model model) {
        CartItemVo cart = cartService.getCartItem(skuId);
        model.addAttribute("item", cart);
        return "success";
    }
    @GetMapping("/checked")
    public String checked(@RequestParam("skuId") Long skuId, @RequestParam("checked") boolean checked) {
        cartService.checked(skuId,checked);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {
        if(num<1)return "redirect:http://cart.gulimall.com/cart.html";
        cartService.countItem(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/delItem")
    public String delItem(@RequestParam("skuId") Long skuId) {
        cartService.delItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
}
